<template>
  <!------------------------------------ 附近门店列表及地图页面 ------------------------------------
    @desc 附近门店选择
    @author kyle
    @date 2021-03-05
    @method
      colseAdress    ———— 关闭地址选择页面
      changeStore  ———— 选择附近门店
  -->
  <div>
    <van-nav-bar
      fixed
      title="附近门店"
      left-arrow
      @click-left="$utils.back($route.path);"
    />
		
    <div class="has-top ">
			
				<div class="bg-white plr-32 pb-14">		
					<!-- 头部定位搜索导航组件 -->
					<top-search
						type="second"
						:location-city="city"
						:val="val"
						:input-style="inputStyle"
						:placeholder="placeholder"
						@showAreaSelect="changeCity"
						@search="search"
					/>				
				</div>
				<div id="container" style="width: 750px;height: 250px;"></div>
				<van-pull-refresh v-model="isLoading" success-text="刷新成功" @refresh="onRefresh">
					<!-- 门店列表 -->
					<div class="bg-white pl-25 pt-25 pb-25 ml-30 mr-30 mt-24 br-16 flex" v-for="(item, index) in shopList"
						:key="index" :style="getStyle(item)" @click="changeStore(item)">
						<div class="cssleft">
							<div class="fs-24 color-dark fw-500">{{ item.Name }}</div>
							<div >
								<svg-icon icon-class="location" class="fs-24 color-gray-light mr-5"/>
								<span class="fs-22 color-gray-light">{{ item.RegionFullName }}{{ item.StreetName }}{{ item.ContactAddress }}</span>
							</div>
							<div >
								<svg-icon icon-class="time" class="fs-24 color-gray-light mr-5"/>
								<span class="fs-22 color-gray-light mt-5">{{ item.BusinessHours || '正在营业'}}</span>
							</div>
						</div>
						<div class="cssright">
							<div class="fs-28 xdtxt tac ">去下单</div>
							<p class="fs-22 color-gray-light tac " v-if="$utils.distanceChange(item.distance)">{{ $utils.distanceChange(item.distance)==='距离未知'?null: $utils.distanceChange(item.distance) }}</p>
							<div class="flex-s-s">
								<div class="circle mr-30">
									<a :href="'tel:'+item.ContactTel">
										<svg-icon icon-class="tel3" class="fs-24 color-gray mt-10 ml-12"/>
									</a>								
								</div>
								<div class="circle2" @click.stop="navigation(item)">
									<svg-icon icon-class="daohang" class="fs-24 color-gray mt-12 ml-15" @goPage="navigation(item)"/>
								</div>
							</div>
						</div>      
					</div>

					<no-data v-if="shopList.length === 0" />
					<p v-if="end===true&&shopList.length!==0" class="tac fs-24 ptb-40 color-gray-light">无更多数据</p>

			 </van-pull-refresh>	
		</div>
		
		<!-- 选择城市 -->
		<transition name="van-slide-right" v-if="isShowSelectCity">
      <div
        style="
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          width: 100%;
          z-index: 1500;
        "
      >
        <SelectCity
          @getCity="getCity"
          @closeCity="closeCity"
          @showRit="showRit"
          :faRit="rightArea"
        ></SelectCity>
      </div>
    </transition>

		<!-- 旧的定位地址选择组件 -->
		<!--<area-select
        v-show="AreaSelect"
        class="animated"
        :class="{ slideInRight: animated == 'slideIn', slideOutRight: animated == 'slideOut' }"
        :current-city="locationCity"
        @closeAreaSelect="closeAreaSelect"
        @selCity="selCity"
        @getCurrentPosition="getCurrentPosition"
    />-->
  </div>
</template>

<script>
import TopSearch from 'components/Search'
import areaSelect from 'components/areaSelect'
import bussinessItem from 'components/bussinessItem'
import noData from 'components/noData'
import SelectCity from "components/address/selectCity";
import { GetStorePage, GetStoreCategoryTree, GetStoreTagList, GetCityIdByCode, GetUserCityId } from 'api/store'
export default {
  name: 'StoreList',
  components: {
    TopSearch,
		areaSelect,
		bussinessItem,
		noData,
		SelectCity
  },

  data() {
    return {
      // 搜索栏配置及数据
      areaShow: true,
      val: '',
      inputStyle: 'inputStyle-3',
      placeholder: '输入门店地址',
      locationCity: {
        ID: 0,
        Name: '定位中...'
      },
			city:'定位中...',
      // 初始化定位flag
      locationInit: false,
      AreaSelect: false,
			shopList:[],
			// 商家分页条件
			recommendCondition: {
        OrderBy: 2,
        PageIndex: 1,
        PageSize: 20,
        CategoryId: 0,
        TagId: 0,
        Name: '',
        CircleIsHide:0
      },
			// 下拉刷新
			isLoading: false,
      isRefresh: false,
      animated: '',
      storeTypeList: [],
      // 允许列表加载(在定位成功或失败后设置true)
      listLoad: false,

      // 滚动状态
      totalAmout: 0,
      scollRequest: true,
      end: false,
      activeCategoryId:0,
		  mapshoplist:[], // 经纬度不为0的门店列表数组
			map: null,
      makerList: [],
			name:'', // 从 门店详情传进来的门店名称
			//postType:null
			locationLng:0, //定位的经度
			locationLat:0,//定位的纬度
			city:'',
			addressDetail:'',
			addressId:'',
			isShowSelectCity: false,
			rightArea: '',
    }
  },
	created() {

		if (this.$route.query.name) {			
			this.name =this.$route.query.name
		}
		//// 如果选择了外送，当前经纬度为默认地址外送地址的经纬度
		//if (this.$route.query.param ) {			
		//	let param = JSON.parse(this.$route.query.param)	
		//	console.log('外送外送',param)		
		//	this.recommendCondition.Lng = param.wLng
		//	this.recommendCondition.Lat = param.wLat
		//	this.locationLng = param.wLng
		//	this.locationLat = param.wLat
		//	if (this.addressId) {
		//		this.city = param.city
		//		this.addressDetail = param.addressDetail
		//		this.addressId = param.addressId
		//		this.search()
		//	} else {
		//		//this.getPosition()
		//		this.GetUserCityId()
		//	}
		//	
		//} else {
		//	console.log('我定位了')
		//	//// 获取定位
		//	//this.getPosition()
		//	this.GetUserCityId()
		//}
		this.getPosition()
		
  },
  watch: {

  },
 
  methods: {
		changeCity() {
      this.isShowSelectCity = true;
      this.rightArea = '3'
    },
		showRit(val) {
      this.rightArea = val
    },
    getCity(cityObj) {
      this.city = cityObj.name;
      this.isShowSelectCity = false;
      this.recommendCondition.Lng = Number(cityObj.lng.toFixed(6))
			this.recommendCondition.Lat = cityObj.lat
			this.locationLng = Number(cityObj.lng.toFixed(6))
			this.locationLat = cityObj.lat
			this.GetCityIdByCode(cityObj.adcode)
			//console.log('cityObj',cityObj)
		
    },
    closeCity() {
      this.isShowSelectCity = false;
    },
    // 关键字搜索商户列表
    search(key) {
      this.recommendCondition.PageIndex = 1
      this.recommendCondition.Name = key
      this.shopList = []
      this.GetStorePage()
    },
		getStyle(item){
				if(item.isActive){
					return {'border':'1px solid #FE4B00'}
				}
				return {}
		},
		changeStore(item, index) {	
			console.log('item',item)
			let id = item.ID
			let lng = this.locationLng
			let lat = this.locationLat
			if (this.addressDetail) {
				this.$router.push(`/shopProductList/${id}?lng=${lng}&lat=${lat}&postType=${this.$route.query.postType}&addressDetail=${this.addressDetail}&addressId=${this.addressId}`)
			} else {
				this.$router.push(`/shopProductList/${id}?lng=${lng}&lat=${lat}&postType=${this.$route.query.postType}`)	
			}
			
    },  
		// 下拉刷新
		onRefresh() {
      if (this.listLoad) {
        this.isRefresh = true
        this.listLoad = false
        this.end = false
        this.recommendCondition.PageIndex = 1
        this.shopList = []
        this.GetStorePage()
      } else {
        this.isLoading = false
      }
    },
    // 列表刷新后的回调
    listRefresh() {
      this.isRefresh = false
      this.isLoading = false
    },
		// 获取商家分页
		GetStorePage() {
      GetStorePage(this.recommendCondition).then(res => {
        if (res) {
          if (res.Data.length && res.Data.length > 0) {
            res.Data.forEach(item => {
              if (!item.Logo && item.ShopSign) {
                item.Logo = item.ShopSign.split(',')[0]
              }		
							item.isActive = (item.Name == this.name) ? true : false	
              this.shopList.push(item)
            })
          }        
          this.totalAmout = res.TotalAmout
          this.scollRequest = true
          this.listLoad = true
          this.isLoading = false
						// DOM初始化完成进行地图初始化
    				this.initAMap()
        }
      })
    },
		goDetail(item) {
      this.scollRequest = false
      console.log(item.ID)
      if(item.IndexUrl){
        window.location.href = item.IndexUrl
      }else{
        this.$router.push({
          path: '/businessDetail/' + item.ID
        })
      }
    },
    // 获取城市id
    GetCityIdByCode(code) {
      GetCityIdByCode({ RegionCode: code }).then(res => {
        if (res) {
          this.locationCity.ID = res.Data
          this.recommendCondition.areaId = res.Data
          const _str = JSON.stringify(this.locationCity)
          //localStorage.setItem('SelectCity', _str)
          // 初始化请求参数
          this.recommendCondition.PageIndex = 1
          this.shopList = []
          // 获取商家列表
          this.GetStorePage()
          // 获取分类列表
          this.GetStoreCategoryTree({ 'regionName': this.locationCity.Name })
        }
      })
    },
    // 获取所属区域
    GetUserCityId() {
      GetUserCityId().then(res => {
        if (res && res.Data) {					
          if (res.Data.ID === 0) {
            this.getCurrentPosition()
          } else {
						this.city = res.Data.Name 
					  this.recommendCondition.cityId = res.Data.ID 
            const _str = JSON.stringify(res.Data)
            //localStorage.setItem('SelectCity', _str)
            //this.getPosition()
						const _GeolocationData = localStorage.getItem('GeolocationData')
						if (_GeolocationData) { // 存在定位缓存
							const _GeolocationObj = JSON.parse(_GeolocationData)
							if (_GeolocationObj.center && _GeolocationObj.center.length > 0) {
								this.recommendCondition.Lng = _GeolocationObj.center[0]
								this.recommendCondition.Lat = _GeolocationObj.center[1]
								this.locationLng = _GeolocationObj.center[0]
								this.locationLat = _GeolocationObj.center[1]
							} else if (_GeolocationObj.position) {
								this.recommendCondition.Lng = _GeolocationObj.position.lng
								this.recommendCondition.Lat = _GeolocationObj.position.lat
								this.locationLng = _GeolocationObj.position.lng
								this.locationLat = _GeolocationObj.position.lat
							}
							this.listLoad = true
							this.isRefresh = true
							console.log('this.recommendCondition',this.recommendCondition)
							this.onRefresh()
						} else {
							// 调用定位获取经纬度
							this.getCurrentPosition(this.city)
						}
						
          }
        }
      })
    },

		// 定位
    getPosition() {
      // 获取当前城市（缓存）
      const _str = localStorage.getItem('SelectCity')
			const _obj = JSON.parse(_str)
      if (_obj.ID != 0) {
        
				console.log('getPosition定位',_obj)
				this.city = _obj.Name
        this.locationCity.Name = _obj.Name
        this.locationCity.ID = _obj.ID
        this.recommendCondition.areaId = _obj.ID
        // 获取经纬度缓存
        const _GeolocationData = localStorage.getItem('GeolocationData')
        if (_GeolocationData) { // 存在定位缓存
          const _GeolocationObj = JSON.parse(_GeolocationData)
          if (_GeolocationObj.center && _GeolocationObj.center.length > 0) {
            this.recommendCondition.Lng = _GeolocationObj.center[0]
            this.recommendCondition.Lat = _GeolocationObj.center[1]
            this.locationLng = _GeolocationObj.center[0]
            this.locationLat = _GeolocationObj.center[1]
          } else if (_GeolocationObj.position) {
            this.recommendCondition.Lng = _GeolocationObj.position.lng
            this.recommendCondition.Lat = _GeolocationObj.position.lat
            this.locationLng = _GeolocationObj.position.lng
            this.locationLat = _GeolocationObj.position.lat
          }
          this.listLoad = true
          this.isRefresh = true
					console.log('this.recommendCondition',this.recommendCondition)
          this.onRefresh()
        } else {
          // 调用定位获取经纬度
          this.getCurrentPosition(_obj.Name)
        }
      } else {
        this.GetUserCityId()
      }
    },
		// 显示地址选择
    showAreaSelect(val) {
      console.log(val)
      const self = this
      self.animated = 'slideIn'
      self.AreaSelect = val
      setTimeout(() => {
        self.animated = ''
        ModalHelper.afterOpen()
      }, 300)
    },
    // 关闭地址选择
    closeAreaSelect(val) {
      const self = this
      self.animated = 'slideOut'
      setTimeout(() => {
        self.AreaSelect = val
        self.animated = ''
        ModalHelper.beforeClose()
      }, 300)
    },
    // 选择城市回调
    selCity(item) {
      console.log(item)
      if (this.locationCity.ID !== item.ID) {
        this.locationCity.ID = item.ID
        this.locationCity.Name = item.Name
        // 手动选择城市后不再进行定位初始化
        const _str = JSON.stringify(item)
        //localStorage.setItem('SelectCity', _str)
        this.locationInit = true
        this.listLoad = true
        this.recommendCondition.areaId = item.ID
        this.onRefresh()
      }
    },
		// 获取缓存定位
		getLocalPosition() {

		},
		// 监听定位
		getCurrentPosition(cityName) {
			const _this = this
			// 对查询条件经纬度赋值0 0
			delete _this.recommendCondition.Lng
			delete _this.recommendCondition.Lat

			_this.locationCity.Name = cityName || '定位中...'
			_this.locationInit = !!cityName
			this.$toast.loading({
				forbidClick: true,
				message: 'loading...',
				loadingType: 'spinner',
				duration: 0
			})
			_this.$geolocation.getCurrentPosition(function(status, result) {
				if (status === 'complete') {
					_this.onComplete(result)
				} else {
					_this.onError(result)
				}
			})
		},

		// 精准定位成功
		onComplete(data) {
			console.log('精准定位成功data',data)
			localStorage.setItem('GeolocationData', JSON.stringify(data))
			this.$toast.clear()
			this.closeAreaSelect(false)
			// 对查询条件经纬度赋值
			this.recommendCondition.Lng = data.position.lng
			this.recommendCondition.Lat = data.position.lat
			this.locationLng= data.position.lng
			this.locationLat = data.position.lat
			if (!this.locationInit) {
				this.locationCity.Name = data.addressComponent.district || data.addressComponent.city
				this.city = data.addressComponent.district || data.addressComponent.city
				const adcode = parseInt(data.addressComponent.adcode.substr(0, 4) + '00').toString()
				this.GetCityIdByCode(adcode)
			} else {
				this.listLoad = true
				this.isRefresh = true
				this.onRefresh()
			}
		},
		// 精准定位失败
		onError(data) {
			console.log('精准定位失败')
			const _this = this
			_this.$geolocation.getCityInfo(function(status, result) {
				if (status === 'complete') {
					_this.onComplete1(result)
				} else {
					_this.onError1(result)
				}
			})
		},
		// ip定位成功
		onComplete1(data) {
			console.log('ip定位成功data',data)
			localStorage.setItem('GeolocationData', JSON.stringify(data))
			this.$toast.clear()
			this.closeAreaSelect(false)
			// 对查询条件经纬度赋值
			this.recommendCondition.Lng = data.center[0]
			this.recommendCondition.Lat = data.center[1]
			this.locationLng = data.center[0]
			this.locationLat = data.center[1]
			// 第一次初始化定位城市
			if (!this.locationInit) {
				this.locationCity.Name = data.city
				const adcode = parseInt(data.adcode.substr(0, 4) + '00').toString()
				this.GetCityIdByCode(adcode)
			} else {
				this.listLoad = true
				this.isRefresh = true
				this.onRefresh()
			}
		},
		// ip定位失败
		onError1(data) {
			console.log('ip定位失败')
			console.log(data)
			this.$toast.clear()
			this.$toast.fail({
				message: '获取定位信息失败，请刷新',
				icon: 'close'
			})
			this.locationCity.Name = '未知'
			setTimeout(() => {
				if (!this.locationInit) {
					this.locationInit = true
					this.listLoad = true
					this.isRefresh = true
					this.onRefresh()
				}
			}, 1000)
		},
		// 打开导航
    navigation(item) {      
      this.$utils.navigation(item)
    },
		initAMap(){
			let self = this;
			// 构建一个经纬度不为0的门店数组
			this.mapshoplist = this.shopList.filter((x)=>{
				return x.Lng != 0;
			})
		
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        zoom: 15, //级别
        center: [this.recommendCondition.Lng, this.recommendCondition.Lat], //中心点坐标
				zoomEnable: true, // 地图是否可缩放，默认值为true
				dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
				doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
        viewMode: "3D", //使用3D视图
        //mapStyle: "amap://styles/darkblue",
      }); //初始化地图
			
			let icon = new AMap.Icon({
        size: new AMap.Size(36, 36), // 图标尺寸
        image: "https://hsy884.oss-cn-hangzhou.aliyuncs.com/upload/2023/04/26/20230426141421929.png", // Icon的图像
        imageSize: new AMap.Size(24, 30), // 根据所设置的大小拉伸或压缩图片
        imageOffset: new AMap.Pixel(0, 0)  // 图像相对展示区域的偏移量，适于雪碧图等
      });
	
      //遍历生成多个标记点
			this.mapshoplist.forEach(x=>{		
				var marker = new AMap.Marker({
					position: [x.Lng,x.Lat],     // 经纬度对象，也可以是经纬度构成的一维数组[118.610037,24.886198]
					map:this.map,
					icon: icon, // 添加 Icon 实例				
					title:x.Name,	
					offset: new AMap.Pixel(-15, -20),		
				
				});
				
				marker.content = x.Name;			
        marker.on('click', this.markerClick);
        //marker.emit('click', {target: marker});
				this.map.add([marker]);
			})
      this.map.setFitView();
		},
		markerClick(e){
					let name = e.target.content
					//console.log('name',name)
					this.mapshoplist.forEach(x=>{
						if (name == x.Name) {
							return x.isActive = true
						}else{
							return x.isActive = false
						}
					})
					var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)});				
					infoWindow.setContent(e.target.content);
          infoWindow.open(this.map, e.target.getPosition());
		}
  }
}
</script>

<style lang="scss" scoped>
.ads-list{
  margin: 0 24px;
  .ads-item{
    background: $colorF;
    padding:30px 20px;
    border-radius: 12px;
    margin-top: 18px;
    .arrow{
      width: 20px;
      height: 20px;
      position: relative;
      &:after {
        top: 0;
        left: 0;
      }
    }
    .ads-item-left{
      width: 40px;
      height: 40px;
      border: 1px solid $colorC;
      border-radius: 100%;
      margin-right: 25px;
    }
    .ads-item-selected{
      background: $color3;
      border-color: $color3;
      position: relative;
      &:after{
        content:'';
        position: absolute;
        top: 6px;
        left: 6px;
        width: 16px;
        height: 8px;
        border: 4px solid;
        border-color: transparent transparent $colorF $colorF;
        transform: rotate(-45deg);
      }
    }
    .ads-default{
      display: inline-block;
      font-size: 24px;
      line-height: 34px;
      padding:0 10px;
      border-radius: 17px;
      margin-right: 12px;
    }
  }
}
.bottom-box{
  padding: 0 30px 44px 30px;
  display:flex;
  align-items: center;
  background: $colorF5;
}
.mapmain {
  height: 500px;
  background: #16ad56;
}
.cssleft{
	width: 464px;
	padding-right: 24px;
	border-right: 1px solid #F2F3FC;
	display: flex;
  flex-direction: column;
	justify-content: space-between;
	
}
.cssright{	
	flex: 1;
	display: flex;
  flex-direction: column;
	justify-content: space-between;
	align-items: center;
	.xdtxt{
		color: #FE4B00;
		font-weight: 600;	
	}
	.circle{
		width: 48px;
		height: 48px;
		background: #FFFFFF;
		border-radius: 50%;
		box-shadow: 0px 4px 18px #e5e5e5;
	}
	.circle2{
		width: 55px;
		height: 55px;
		background: #FFFFFF;
		border-radius: 50%;
		box-shadow: 0px 4px 18px #e5e5e5;
	}
}

</style>

